package com.controller;

import com.entity.*;
import com.github.pagehelper.Page;
import com.service.ActivityService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    private  String path = new File(System.getProperty("user.dir")).toString()+"/static/img/";

    @PostMapping("addAcivity")
    private Object add(@RequestBody Activity activity){
        System.out.println(activity);
        Object object= activityService.addActivity(activity);
        return object;
    }

    /*
    查询活动
    paging{
        page:页数
        limit:多少条数据
    }
     */
    @PostMapping("queryProJectsPage")
    public Object selectProJectsPage(@RequestBody Paging paging ) {
        Page<ProJectsPage> page = (Page<ProJectsPage>) activityService.selectProJectsPage(paging);
        return "{\"total\":"+page.getTotal()+",\"devices\":"+JSONArray.fromObject(page)+"}";
    }


    /**
     * 添加伙食安排
     *
     *
     */
    @PostMapping("addFood")
    public Object addFood(@RequestBody Food food){
        return activityService.addFood(food);
    }
    /*
        添加活动安排
     */
    @PostMapping("addProplan")
    public Object addProplan(@RequestBody Proplan proplan){
        return  activityService.addProplan(proplan);
    }
    /*
              删除伙食安排
     */
    @GetMapping("deleteFood")
    public Object deleteFood(int foodID){
        return activityService.deleteFood(foodID);
    }
    /*
             删除活动安排
   */
    @GetMapping("deleteProplan")
    public Object deleteProplan(int proplanID){
        return  activityService.deleteProplan(proplanID);
    }
    /*
    食宿安排
    {
        proID：活动id
    }
     */
    @PostMapping("queryFood")
    public List<Food> selectFoodByID(@RequestBody String data){
        int id = (int)JSONObject.fromObject(data).get("proID");
        return activityService.selectFoodByID(id);
    }
    /*
    日程安排
     proID：活动id
     */
    @PostMapping("queryProplan")
    public Object selectProplanByID(@RequestBody String data){
        int id = (int)JSONObject.fromObject(data).get("proID");
        return activityService.selectProplanByID(id);
    }
    @PostMapping(value = "multiFileUpload")
    public String multiFileUpload(HttpServletRequest request,String  data) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
        Scenery scenery = (Scenery)JSONObject.toBean(JSONObject.fromObject(data),Scenery.class);
        if (files.size() == 0){
            return "文件为空";
        }else{
            System.out.println(files);
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return "上传多个文件时,某个文件大小为空,请检查!!";
                } else {
                    String fileName = file.getOriginalFilename();
                    System.out.println(fileName);
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    long size = file.getSize();
                    System.out.println(path+"/static/img/activity/"+scenery.getProID() +"/"+scenery.getImg()+suffixName);
                    File dest = new File(path+"/activity/"+scenery.getProID() +"/"+scenery.getImg());
                    System.out.println(dest.getParentFile());
                    if (!dest.getParentFile().exists()) {
                        System.out.println(dest.getParentFile());
                        dest.getParentFile().mkdirs();
                    }
                    try {

                        file.transferTo(dest);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println(scenery);
       int state = activityService.addScenery(scenery);
        return "{\"state\":"+state+"}";
    }

    @PostMapping("selectSceneryByID")
    public List<Scenery> selectSceneryByID(@RequestBody String data){
        int proID = (int)JSONObject.fromObject(data).get("proID");
        return activityService.selectSceneryByID(proID);
    }
    @PostMapping("deleteSceneryByID")
    public String deleteSceneryByID(@RequestBody Scenery scenery){

        File file = new File(path+"activity/"+scenery.getProID()+"/"+scenery.getImg());
        if (file.exists()) {
            file.delete();
            activityService.deleteSceneryByID(scenery);
            return "{\"state\":"+"\"已删除\""+"}";

        }
        int state = activityService.deleteSceneryByID(scenery);
        System.out.println(state);
        return "{\"state\":"+"\"删除完成\""+"}";
    }
    @PostMapping("uploadFile")
    public String uploadHandoverForm(HttpServletRequest request,String path){
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        if (files.size() == 0){
            return "文件为空";
        }else{
            System.out.println(files);
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    return "{\"state\":"+"\"上传多个文件时,某个文件大小为空,请检查!!\""+"}";
                } else {
                    String fileName = file.getOriginalFilename();

                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    long size = file.getSize();
                    File dest = new File(this.path+path);
                    System.out.println(this.path+path);
                    if (!dest.getParentFile().exists()) {
                        System.out.println(dest.getParentFile());
                        if (!dest.getParentFile().mkdirs()){
                            return "{\"state\":"+"\"创建目录失败，检查路径\""+"}";
                        }

                    }
                    try {

                        file.transferTo(dest);

                    } catch (IOException e) {
                        e.printStackTrace();
                        return "{\"state\":"+"\"上传失败\""+"}";
                    }
                }
            }
        }
        return "{\"state\":"+"\"上传成功\""+"}";
    }


    @PostMapping("returnImg")
    public List<String> returnImg(@RequestBody String  data){
        String path = (String) JSONObject.fromObject(data).get("path");
        List<String> files = new ArrayList<String>();
        File file = new File(this.path+path);
        System.out.println(this.path+path);
        File[] tempList = file.listFiles();
        if (tempList == null){
//            return "目录为空";
            return new  ArrayList<String>();
        }
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
              //  files.add(tempList[i].toString().substring(tempList[i].toString().lastIndexOf("\\")));
                //文件名，不包含路径
                String fileName = tempList[i].getName();
                files.add(fileName);
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
       // return JSONArray.fromObject(files).toString();
        return files;
    }

    @PostMapping("uploadFileTxt")
    public Object uploadFileTxt(@RequestBody String data){
        System.out.println(new Date());
        String txt = (String)JSONObject.fromObject(data).get("file");

        String path = (String)JSONObject.fromObject(data).get("path");
//        if (proID == null){
//            return "{\"state\":"+"\"proID为空\""+"}";
//        }
        File file = new File(this.path+path);
        System.out.println(file.getParentFile());
        if (!file.getParentFile().exists()) {
            System.out.println(file.getParentFile());
            if (!file.getParentFile().mkdirs()){
                return "{\"state\":"+"\"创建目录失败，检查路径\""+"}";
            }
        }
        try {
            FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(txt);
            bw.close();
        }catch (IOException e){
            e.printStackTrace();
            return "{\"state\":"+"\"添加失败\""+"}";
        }
        System.out.println(new Date());
        return "{\"state\":"+"\"添加完成\""+"}";

    }
    @PostMapping("returnFileText")
    public Object returnFileText(@RequestBody String data){
        String path =  (String)JSONObject.fromObject(data).get("path");
//        if (proID == null){
//            return "{\"state\":"+"\"检查参数\""+"}";
//        }
        File file = new File(this.path+path);
//        System.out.println(this.path+"txt\\"+proID+"\\data.txt");
        if(!file.exists()){
            return "{\"state\":"+"\"文件不存在\""+"}";
        }
        try{
            FileReader inOne = new FileReader(file);
            BufferedReader inTwo = new BufferedReader(inOne);
            StringBuilder txt = new StringBuilder();
            String i;
            while (( i= inTwo.readLine()) != null){
                txt.append(i);
            }
            inOne.close();
            inTwo.close();
            return txt;
        }catch (IOException e){
            e.printStackTrace();
            return "{\"state\":"+"\"添加失败\""+"}";
        }
    }
    /*
     input查询
     */
    @PostMapping("queryProJectsPageByName")
    public Object queryProJectsPageByName(@RequestBody String data){
        String activeName = (String) JSONObject.fromObject(data).get("activeName");
        return activityService.queryProJectsPageByName(activeName);
    }

    /*
      添加基地
     */
    @PostMapping("addBase")
    public Object addBase(@RequestBody Base base){
        return activityService.addBase(base);
    }
    /*
      查询基地
     */
    @PostMapping("queryBases")
    public Object queryBases(){
        return activityService.selectBases();
    }
    /*
        删除基地
        baseName：基地名
     */
    @PostMapping("deleteBaseByName")
    public Object deleteBaseByName(@RequestBody  String data){
        String baseName = (String) JSONObject.fromObject(data).get("baseName");
        return activityService.deleteBaseByName(baseName);
    }



    /*
        查询基地是否存在
        baseName：基地名
     */
    @PostMapping("queryBase")
    public Object queryBase(@RequestBody  String data){
        String baseName = (String) JSONObject.fromObject(data).get("baseName");
        return activityService.selectBaseByName(baseName);
    }


    /*
      添加旅行社
    */
    @PostMapping("addAgency")
    public Object addAgency(@RequestBody Agency agency){
        return activityService.addAgency(agency);
    }
    /*
         查询所有旅行社
    */
    @PostMapping("queryAgencys")
    public Object queryAgencys(){
        return activityService.selectAgencys();
    }

    /*
       查询旅行社是否存在
       travelAgencyValue：旅行社名
    */
    @PostMapping("queryAgency")
    public Object queryAgency(@RequestBody String data){
        String travelAgencyValue = (String)JSONObject.fromObject(data).get("travelAgencyValue");
        return activityService.selectAgency(travelAgencyValue);
    }

    /*
     删除旅行社
     travelAgencyValue:旅行社名字
    */
    @PostMapping("deleteAgency")
    public Object deleteAgency(@RequestBody String data){
        String travelAgencyValue = (String)JSONObject.fromObject(data).get("travelAgencyValue");
        return activityService.deleteAgencyByName(travelAgencyValue);
    }
}
